﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace QuickJob.forms
{
    public partial class QuickDownPictureBat : Form
    {
        /// <summary>
        /// 所有连接项
        /// </summary>
        List<string> listUrl = new List<string>();

        System.Threading.Thread thread;


        //下载事件
        event onDownloadUrl ondownload;

        public QuickDownPictureBat()
        {
            InitializeComponent();

            this.textBox_BatFile.MouseDoubleClick += textBox_BatFile_MouseDoubleClick;
            this.textBox_BatOutPutDir.MouseDoubleClick += textBox_BatOutPutDir_MouseDoubleClick;
            this.textBox_BatXiShui.MouseDoubleClick += textBox_BatXiShui_MouseDoubleClick;

            ondownload += QuickDownPictureBat_ondownload;

        }

        void QuickDownPictureBat_ondownload(object sender, QuickDownPictureBat.onDownloadUrlArgs arg)
        {
            if (this.InvokeRequired)
            {
                onDownloadUrl d = new onDownloadUrl(QuickDownPictureBat_ondownload);
                this.BeginInvoke(d, new object[] { sender, arg });
            }
            else
            {
                this.progressBar_QDP_Bat.Maximum = arg.tp.urls.Count;
                this.progressBar_QDP_Bat.Value = arg.currentline;
                this.richTextBox1.AppendText(string.Format("行:{0},为:{1}\r\n",arg.currentline,arg.tp.urls[arg.currentline-1]));
                this.richTextBox1.AppendText(arg.msg);

                this.label_TotalLine.Text = "/"+arg.tp.urls.Count.ToString();
                this.label_CurrentLine.Text = "/" + arg.currentline.ToString();
                this.label_PictureCountALL.Text = "/" + arg.ValidLine.ToString();
                this.label_PictureCount.Text = arg.DownCount.ToString();


            }
        }

        void textBox_BatXiShui_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.Title = "选择　洗水唛　的图片文件：xxx.jpeg  or jpg";
            if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (file.CheckFileExists == false)
                {

                    this.richTextBox1.AppendText("洗水唛文件不存在");
                }
                else
                {
                    this.textBox_BatXiShui.Text = file.FileName;
                }
            }
        }

        void textBox_BatOutPutDir_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog();
            dilog.Description = "请选择文件夹";
            if (dilog.ShowDialog() == DialogResult.OK || dilog.ShowDialog() == DialogResult.Yes)
            {
                String Dir = dilog.SelectedPath;
                this.textBox_BatOutPutDir.Text = Dir;
            }
        }

        void textBox_BatFile_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.Title = "选择批量网址，一行一个";
            if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (file.CheckFileExists == false)
                {

                    this.richTextBox1.AppendText("洗水唛文件不存在");
                }
                else
                {
                    this.textBox_BatFile.Text = file.FileName;
                }
            }
        }


        string ToShangCheng(string sc)
        {
            string ShangeCheng = "";
            try
            {
                // EcanConvertToCh ec = new EcanConvertToCh();
                String ss = PinYinConverter.GetFirst(sc); //ec.convertCh(textBox_shangCheng.Text);

                if (ss.Split('#').Length >= 2)
                {
                    ShangeCheng = ss;
                }
                else
                {

                    string[] s = ss.Split('-');

                    if (s.Length < 2)
                    {
                        throw (new Exception("商城格式错误"));
                    }

                    for (int i = 0; i < s.Length; i++)
                    {

                        if (i == 0) ShangeCheng = s[0] + "#";
                        else if (i == s.Length - 1) ShangeCheng = ShangeCheng + "#" + s[i];
                        else
                        {
                            if (i != s.Length - 2) ShangeCheng = ShangeCheng + s[i] + "-";
                            else ShangeCheng = ShangeCheng + s[i];
                        }
                    }
                }
                ShangeCheng = ShangeCheng.Replace(" ", "");

                return ShangeCheng;

            }
            catch { }

            return null;
            
        }


        bool DownloadAUrl(string url, int line,string outputDir, string xiShuiMai,ref string outmessage)
        {
            try {
                outmessage = "";

                htmlOper op = new htmlOper();

                //读取信息
                op.HtmlLoadData(url);
                List<string> pics = op.HtmlGetAllPictures();
                op.HtmlGetAllPrices();

                string JiaGe = op.HtmlGetPriceString();
                string ShangCheng = op.HtmlGetShangCheng();
                string HuoHao = op.HtmlGetHuoHao();

                try
                {
                    HuoHao = HuoHao.Replace(" ", "").Replace("#", "");
                    ShangCheng = ToShangCheng(ShangCheng);
                }
                catch { }

                //信息转换
                if (JiaGe == null || ShangCheng == null || HuoHao == null)
                {
                    //出错，本连接不下载
                    outmessage += string.Format("信息错误:商城{0},货号{1},价格{2}\r\n", ShangCheng, HuoHao, JiaGe);
                    outmessage += string.Format("下载出错(行:{0})(Url:{1})\r\n", line, url);
                    return false;
                }

#region  下载大图
                //下载大图保存
                try
                {


                    if (Directory.Exists(outputDir) == false)
                        Directory.CreateDirectory(outputDir);
                    string newPath = System.IO.Path.Combine(outputDir, ShangCheng + "#" + HuoHao + "#" + JiaGe);

                    if (Directory.Exists(newPath))
                        outmessage += "文件夹已经存在\r\n";
                    else
                    {

                        Directory.CreateDirectory(newPath);
                        outmessage += ("创建目录:" + newPath + "\r\n");
                    }

                    //添加文件 
                    try
                    {
                        //String enter = "\r\n";
                        //FileStream fs = File.Create(newPath + "\\" + "html.html");
                        //String html = op.HtmlToDocumentation(url, op.HtmlGetTitle());
                        //byte[] data = System.Text.Encoding.Default.GetBytes(html + "\t" + "\r\n");
                        //fs.Write(data, 0, data.Length);
                        //fs.Close();
                        op.HtmlSaveDocumentation(newPath);

                        ///////////////////////////////////////

                        //复制洗水唛
                        try
                        {
                            string filepath = System.IO.Path.Combine(newPath, "xishuimai.jpeg");
                            System.IO.File.Copy(xiShuiMai, filepath);
                        }
                        catch { }

                        //加载图片
                        Size sPic = new Size(400, 400);
                        List<string> dpics = op.HtmlDownloadBigPictures(sPic.Width, sPic.Height, newPath, 180, 180);

                        foreach (string pic in dpics)
                        {
                            outmessage += ("下载：" + pic + "\r\n");
                        }

                        if (dpics != null && dpics.Count > 0) outmessage += ("已下载：" + dpics.Count + "张");
                        else outmessage += ("没有大于" + sPic.Width + "* " + sPic.Height + " 的图片\r\n");


                    }
                    catch
                    {
                        outmessage += (string.Format("下载出错(行:{0})(Url:{1})\r\n", line, url));
                        return false;
                    }

                }
                catch
                {
                    outmessage += (string.Format("下载出错(行:{0})(Url:{1})\r\n", line, url));
                    return false;

                }


                return true;
#endregion

            }
            catch
            {
                outmessage += (string.Format("下载出错(行:{0})(Url:{1})\r\n", line, url));
                return false;
            }


            return false;
        }

        class onDownloadUrlArgs : EventArgs
        {
            /// <summary>
            /// 线程参数
            /// </summary>
            public ThreadPara tp;

            /// <summary>
            /// 有效地址
            /// </summary>
            public int ValidLine;

            /// <summary>
            /// 当线行
            /// </summary>
            public int currentline;


            /// <summary>
            /// 已经下载数
            /// </summary>
            public int DownCount;


            /// <summary>
            /// 打印信息
            /// </summary>
            public string msg;

        }

        delegate void onDownloadUrl(object sender, onDownloadUrlArgs arg);


        
        class ThreadPara
        {
            public List<string> urls;
            public string outputDir;
            public string xiShuiMai;
        }

        void threadRun(object param)
        {
           ThreadPara tp = (ThreadPara)param;
           int ValidCount = 0;
           if (tp.urls == null || tp.urls.Count <= 0) return;
            int DownCount = 0;

            ///有效行数
            foreach (string l in tp.urls)
            {
                if (l != null && l != "") { ValidCount++; }
            }


            for(int i = 0;i<tp.urls.Count;i++)
            {
                string url = tp.urls[i];
                string outmessage = "";

                if (url == null || url == "")
                {
                    outmessage = "";
                }
                else
                {
                    if (DownloadAUrl(url, i, tp.outputDir, tp.xiShuiMai, ref outmessage) == true)
                        DownCount++;

                }

                if (ondownload != null)
                {
                    onDownloadUrlArgs arg = new onDownloadUrlArgs();
                    arg.tp = tp;
                    arg.DownCount = DownCount;
                    arg.currentline = i+1;
                    arg.msg = outmessage;
                    arg.ValidLine = ValidCount;
                    ondownload(null, arg);
                }


            }
        }


        private void 开始批量下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int currentline = 0;
            try
            {

                //打开文件
                StreamReader rd;
                String fn = this.textBox_BatFile.Text;
                try
                {
                    rd = new StreamReader(fn, Encoding.Default);
                }
                catch (Exception er)
                {
                    System.Console.WriteLine("logSettingRecover无法打开:" + fn);
                    MessageBox.Show("logSettingRecover无法打开文件" + fn);
                    return;
                }

                listUrl.Clear();
                ///读入文件
                for (string line = rd.ReadLine(); line != null; line = rd.ReadLine())
                { 
                    listUrl.Add(line);
                }
                rd.Close();

                if(listUrl.Count<=0){MessageBox.Show("没有可以下载的网址");return;}

                progressBar_QDP_Bat.Maximum = listUrl.Count;
                progressBar_QDP_Bat.Value = 0;

                thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(threadRun));

                ThreadPara p = new ThreadPara();
                p.urls = listUrl;
                p.outputDir = this.textBox_BatOutPutDir.Text;
                p.xiShuiMai = this.textBox_BatXiShui.Text;
                thread.Start(p);

            }
            catch { MessageBox.Show("出错"); }
        }


        private void 停止批量下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (thread != null)
            {
                thread.Abort();
                MessageBox.Show("下载已经终止");
            }
        }
    }
}
